const http = require("http");
const fs = require("fs");
const path = require("path");
const cheerio = require("cheerio");

const newsList = [];
const filePath = path.join(__dirname,"/news.html");
fs.readFile(filePath,(err,data)=>{
    if(err){
        console.log(err);
    }else{
        htmlStr = data.toString();
    }
    })
http.createServer((req,res)=>{
    var reqUrl = req.url;
    if(reqUrl=='/'){
        var $ = cheerio.load(htmlStr);
        $(".news-model a").each((i,el)=>{
            if($(el).text().indexOf('2018')>-1){
                const newObj = {newsTitle:"",createTime:""};
                newObj["newsTitle"]=$(el).text();
                newObj.createTime=$(el).next().text();
                newsList.push(newObj);
            }
        })
        const list = JSON.stringify(newsList);
        res.writeHeader(200,{'Content-Type':'text/plain;charset=utf-8'});
        res.end(list);
    }
}).listen(8081)